#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <sys/ioctl.h>
#include <string.h>
#include <errno.h>
#include <sys/mman.h>
#include <linux/videodev2.h>
#include <linux/fb.h>
#include "../include/carama.h"

//能正常识别吗?


cam_buf_info buf_infos[FRAMEBUFFER_COUNT];
cam_fmt cam_fmts[FRAMEBUFFER_COUNT];




// 设备初始化
// 成功了就返回ID号
int v4l2_dev_init(const char* device)
{
    int v4l2_fd = -1;
    struct v4l2_capability cap = {0};
    /* 打开摄像头 */
    v4l2_fd = open(device, O_RDWR);
    if (0 > v4l2_fd) {
        fprintf(stderr, "open error: %s: %s\n", device, strerror(errno));
        return -1;
    }
    /* 查询设备功能 */
    ioctl(v4l2_fd, VIDIOC_QUERYCAP, &cap);
    /* 判断是否是视频采集设备 */
    if (!(V4L2_CAP_VIDEO_CAPTURE & cap.capabilities)) {
        fprintf(stderr, "Error: %s: No capture video device!\n", device);
        close(v4l2_fd);
        return -1;
    }
    return v4l2_fd;
}

//列举所有支持的像素格式
// 假如说最大不超过10种把
void v4l2_enum_format(int v4l2_fd)
{
    struct v4l2_fmtdesc fmtdesc = {0};
    /* 枚举摄像头所支持的所有像素格式以及描述信息 */
    fmtdesc.index = 0;
    fmtdesc.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
    // 从第0个依次列举
    while(0 == ioctl(v4l2_fd,VIDIOC_ENUM_FMT, &fmtdesc)) {
        cam_fmts[fmtdesc.index].pixelformat = fmtdesc.pixelformat;
        strcpy((char*)cam_fmts[fmtdesc.index].description, (char*)fmtdesc.description);
        fmtdesc.index++;
    }
}

//打印所有的参数 包括pixel_format 分辨率  帧数

void v4l2_print_format(int v4l2_fd)
{
    struct v4l2_frmsizeenum frmsize = {0};
    struct v4l2_frmivalenum frmival = {0};
    int i;
    // 先设定好type
    frmsize.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
    frmival.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
   for (i = 0; cam_fmts[i].pixelformat; i++) {
        // 某种格式
        printf("format<0x%x>, description<%s>\n", cam_fmts[i].pixelformat,
            cam_fmts[i].description);
        /* 枚举出摄像头所支持的所有视频采集分辨率 */
        frmsize.index = 0;
        frmsize.pixel_format = cam_fmts[i].pixelformat;
        frmival.pixel_format = cam_fmts[i].pixelformat;
        
        while (0 == ioctl(v4l2_fd, VIDIOC_ENUM_FRAMESIZES, &frmsize)) {
            printf("size<%d*%d> ",
            frmsize.discrete.width,
            frmsize.discrete.height);
            frmsize.index++;

            // 所支持的帧率
            frmival.index = 0;
            frmival.width = frmsize.discrete.width;
            frmival.height = frmsize.discrete.height;

            while (0 == ioctl(v4l2_fd, VIDIOC_ENUM_FRAMEINTERVALS, &frmival)) {
                printf("<%dfps>", frmival.discrete.denominator / frmival.discrete.numerator);
                frmival.index++;
            }
            printf("\n");
        }
        printf("\n");
        
    }
}

// 传入指针 因为ioctl可能会把这个值给改了

int v4l2_set_format(int v4l2_fd,
                struct v4l2_format* fmt,unsigned char fps)
{
    // 设置完之后坑不会都按照自己想的来
    // 所以可以看看fmt 有没有被改 或者被改成啥了
    struct v4l2_streamparm streamparm = {0};
    if (0 > ioctl(v4l2_fd, VIDIOC_S_FMT, fmt)) {
        fprintf(stderr, "ioctl error: VIDIOC_S_FMT: %s\n", strerror(errno));
        return -1;
    }

     /*** 判断是否已经设置为我们要求的 RGB565 像素格式
     如果没有设置成功表示该设备不支持 RGB565 像素格式 */
     //不支持就算了先按照不支持的来

    printf("视频帧大小<%d * %d>\n", fmt->fmt.pix.width, fmt->fmt.pix.height);

    /* 获取 streamparm */
    // 主要是看看支不支持设置视频的帧率
    ioctl(v4l2_fd, VIDIOC_G_PARM, &streamparm);
    
    if (V4L2_CAP_TIMEPERFRAME & streamparm.parm.capture.capability) {
        streamparm.parm.capture.timeperframe.numerator = 1;
        streamparm.parm.capture.timeperframe.denominator = fps;//30fps
        if (0 > ioctl(v4l2_fd, VIDIOC_S_PARM, &streamparm)) {
            fprintf(stderr, "ioctl error: VIDIOC_S_PARM: %s\n", strerror(errno));
            return -1;
        }
    }
    return 0;
}



int v4l2_init_buffer(int v4l2_fd)
{
    struct v4l2_requestbuffers reqbuf = {0};
    struct v4l2_buffer buf = {0};

    /* 申请帧缓冲 */
    reqbuf.count = FRAMEBUFFER_COUNT; //帧缓冲的数量
    reqbuf.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
    reqbuf.memory = V4L2_MEMORY_MMAP;
    if (0 > ioctl(v4l2_fd, VIDIOC_REQBUFS, &reqbuf)) {
        fprintf(stderr, "ioctl error: VIDIOC_REQBUFS: %s\n", strerror(errno));
        return -1;
    }

    // 建立内存映射
    buf.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
    buf.memory = V4L2_MEMORY_MMAP;
    for (buf.index = 0; buf.index < FRAMEBUFFER_COUNT; buf.index++) {
        ioctl(v4l2_fd, VIDIOC_QUERYBUF, &buf);
        buf_infos[buf.index].length = buf.length;
        buf_infos[buf.index].start = mmap(NULL, buf.length,
                        PROT_READ | PROT_WRITE, MAP_SHARED,v4l2_fd, buf.m.offset);
        if (MAP_FAILED == buf_infos[buf.index].start) {
            perror("mmap error");
            return -1;
        }
    }

    /* 入队操作 */
    for (buf.index = 0; buf.index < FRAMEBUFFER_COUNT; buf.index++) {
        if (0 > ioctl(v4l2_fd, VIDIOC_QBUF, &buf)) {
            fprintf(stderr, "ioctl error: VIDIOC_QBUF: %s\n", strerror(errno));
            return -1;
        }
    }
    return 0;
}

// 开启视频流
int v4l2_stream_on(int v4l2_fd)
{
    /* 打开摄像头、摄像头开始采集数据 */
    // 枚举类型等于类型
    enum v4l2_buf_type type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
    if (0 > ioctl(v4l2_fd, VIDIOC_STREAMON, &type)) {
        fprintf(stderr, "ioctl error: VIDIOC_STREAMON: %s\n", strerror(errno));
        return -1;
    }
    return 0;
}


